package com.jiyun.controller;

import com.aliyun.oss.OSS;
import com.aliyun.oss.OSSClientBuilder;
import com.aliyun.oss.model.GeneratePresignedUrlRequest;
import com.jiyun.common.result.Result;

import com.jiyun.entity.Technician;
import jakarta.servlet.http.HttpServletResponse;
import org.apache.commons.io.IOUtils;
import org.springframework.web.bind.annotation.*;
import org.springframework.beans.factory.annotation.Autowired;
import com.jiyun.service.TechnicianService;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.net.URL;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.time.Duration;
import java.time.LocalTime;
import java.util.List;
import java.util.UUID;


/**
 * (Technician)表控制层
 *
 * @author LYT
 * @since 2025-01-16 18:33:05
 */
@RestController
@RequestMapping("technician")
public class TechnicianController {

    @Autowired
    private TechnicianService technicianService;

    /*
     * 理疗师查询所有数据
     */
    @PostMapping("/findAll")
    public Result<List<Technician>> findAll(@RequestBody Technician technician){
        return Result.ok(technicianService.findAll(technician));
    }

    @PostMapping("/selectStatus")
    public void selectStatus(@RequestBody Technician technician) {
        technicianService.selectStatus(technician);
    }

    @GetMapping("/download")
    public void download(String name, HttpServletResponse response) throws IOException {
        // 创建文件输入流，路径为D盘img文件夹下，文件名由参数name指定
        FileInputStream inputStream = new FileInputStream("D:\\images\\" + name);
        // 将文件输入流复制到HttpServletResponse的输出流中，使用户可以下载文件
        IOUtils.copy(inputStream, response.getOutputStream());
    }
    @PostMapping("/upload")
    public String upload(@RequestParam("file") MultipartFile file) throws IOException {
        // 获取上传文件的原始名称
        String originalFileName = file.getOriginalFilename();
        if (originalFileName == null || originalFileName.isEmpty()) {
            throw new IllegalArgumentException("文件名不能为空");
        }
        // 获取文件扩展名
        String fileExtension = "";
        int lastDotIndex = originalFileName.lastIndexOf('.');
        if (lastDotIndex > 0) {
            fileExtension = originalFileName.substring(lastDotIndex);
        }
        // 生成唯一的文件名
        String uniqueFileName = UUID.randomUUID().toString() + fileExtension;
        // 构建目标文件路径
        Path targetLocation = Paths.get("D:\\images", uniqueFileName);
        // 检查目标文件是否存在，如果存在则删除
        File targetFile = targetLocation.toFile();
        if (targetFile.exists()) {
            Files.delete(targetLocation);
        }
        // 检查并创建目标目录
        Files.createDirectories(targetLocation.getParent());
        // 将文件写入目标位置
        file.transferTo(targetLocation);
        // 返回文件名作为响应
        return uniqueFileName;
    }
//    @PostMapping("/add")
//    public Result add(
//            @RequestParam("name") String name,
//            @RequestParam("age") Integer age,
//            @RequestParam("gender") String gender,
//            @RequestParam("phone") String phone,
//            @RequestParam("city") String city,
//            @RequestPart("file") MultipartFile file) {
//
//        // 处理文件上传
//        String fileName = UUID.randomUUID().toString() + "_" + file.getOriginalFilename();
//        String filePath = "uploads/" + fileName;
//        Path path = Paths.get(filePath);
//        try {
//            Files.createDirectories(path.getParent());
//            Files.copy(file.getInputStream(), path);
//        } catch (IOException e) {
//            e.printStackTrace();
//            return Result.fail("文件上传失败");
//        }
//
//        // 创建 Technician 对象并设置属性
//        Technician technician = new Technician();
//        technician.setTechnicianName(name);
//        technician.setAge(age);
//        technician.setSex(gender);
//        technician.setPhone(phone);
//        technician.setCity(city);
//        technician.setStatus(0);
//        technician.setServiceTotal(0);
//        technician.setLove(0);
//        technician.setSay(0);
//        technician.setSalary(20);
//        technician.setDistance(15.0);
//        technician.setEarlyTime(LocalTime.now());
//        technician.setRating("0.0");
//        technician.setLevel("0");
//        technician.setCollect("0");
//        technician.setImg(filePath); // 设置图片路径
//
//        // 保存 Technician 对象
//        technicianService.save(technician);
//        return Result.ok();
//    }


    private static final String ENDPOINT = "https://oss-cn-beijing.aliyuncs.com";
    private static final String ACCESS_KEY_ID = "LTAI5tRwVJqmVXE9ym1o7Z3r";
    private static final String ACCESS_KEY_SECRET = "OqHoz9iZnABH9Y3q9aOsF7Gvjz18se";
    private static final String BUCKET_NAME = "touxiangsc";

    @PostMapping("/add")
    public Result add(
            @RequestParam("name") String name,
            @RequestParam("age") Integer age,
            @RequestParam("gender") String gender,
            @RequestParam("phone") String phone,
            @RequestParam("city") String city,
            @RequestPart("file") MultipartFile file) {

        // 生成文件名
        String fileName = UUID.randomUUID().toString() + "_" + file.getOriginalFilename();

// 初始化OSS客户端
        OSS ossClient = new OSSClientBuilder().build(ENDPOINT, ACCESS_KEY_ID, ACCESS_KEY_SECRET);

        try {
            // 上传文件到OSS
            ossClient.putObject(BUCKET_NAME, fileName, file.getInputStream());

            // 生成带有签名的 URL，有效期为 1 小时
            GeneratePresignedUrlRequest request = new GeneratePresignedUrlRequest(BUCKET_NAME, fileName);
            request.setExpiration(java.util.Date.from(java.time.Instant.now().plus(Duration.ofHours(1))));
            URL url = ossClient.generatePresignedUrl(request);

            // 获取文件的URL
            String fileUrl = url.toString();

            // 创建 Technician 对象并设置属性
            Technician technician = new Technician();
            technician.setTechnicianName(name);
            technician.setAge(age);
            technician.setSex(gender);
            technician.setPhone(phone);
            technician.setCity(city);
            technician.setStatus(0);
            technician.setServiceTotal(0);
            technician.setLove(0);
            technician.setSay(0);
            technician.setSalary(20);
            technician.setDistance(15.0);
            technician.setEarlyTime(LocalTime.now());
            technician.setRating("0.0");
            technician.setLevel("0");
            technician.setCollect("0");
            technician.setImg(fileUrl); // 设置图片路径

            // 保存 Technician 对象到数据库
            technicianService.save(technician);
            System.out.println("文件上传成功，文件路径为：" + fileUrl);
            return Result.ok().message("文件上传成功");
        } catch (Exception e) {
            e.printStackTrace();
            return Result.fail("文件上传失败");
        } finally {
            // 关闭OSS客户端
            if (ossClient != null) {
                ossClient.shutdown();
            }
        }
    }
}

